﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Phone.Tasks;
using System.ComponentModel;
using Windows.Phone.UI.Input;
using ImageTools;
using ImageTools.IO.Gif;

namespace iMusik
{
    public partial class PlayVideo : PhoneApplicationPage
    {
        private DispatcherTimer _timer;
        private MediaPlayerLauncher _mediaPlayerLauncher;
        private List<iMusik.Mp3ZingOnline.Mp3Video> _listVideo;
        private int _currentVideo = 0;
        private int _count = 0;

        const int prevButton = 0;
        const int playButton = 1;
        const int nextButton = 2;

        public PlayVideo()
        {
            InitializeComponent();

            IntMedia();

            BackKeyPress += PlayVideo_BackKeyPress;
        }

        private void PlayVideo_BackKeyPress(object sender, CancelEventArgs e)
        {
            string uri = "/Mp3ZingPage.xaml";
            NavigationService.Navigate(new Uri(uri, UriKind.Relative)); 
        }

        private void UpdateButtons(bool prevBtnEnabled, bool playBtnEnabled, bool nextBtnEnabled)
        {
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[prevButton])).IsEnabled = prevBtnEnabled;
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).IsEnabled = playBtnEnabled;
            ((ApplicationBarIconButton)(ApplicationBar.Buttons[nextButton])).IsEnabled = nextBtnEnabled;
        }

        private void UpdateBackAndNextButtons()
        {
            if (_currentVideo == 0)
            {
                UpdateButtons(false, true, true);
                return;
            }
            if (_currentVideo == _listVideo.Count - 1)
            {
                UpdateButtons(true, true, false);
                return;
            }
            UpdateButtons(true, true, true);           
        }

        private void UpdatePlayButton()
        {
            if (PlayerVideo.CurrentState == MediaElementState.Playing)
            {
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).IconUri = new Uri("/Assets/Icons/appbar.transport.pause.rest.png", UriKind.Relative);
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).Text = "Pause";
            }
            else
            {
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).IconUri = new Uri("/Assets/Icons/appbar.transport.play.rest.png", UriKind.Relative);
                ((ApplicationBarIconButton)(ApplicationBar.Buttons[playButton])).Text = "Play";
            }
        }

        private void UpdateState(object sender, EventArgs e)
        {
            sldPosition.Value = (int)PlayerVideo.Position.TotalSeconds;

            TimeSpan position = new TimeSpan();
            position = PlayerVideo.Position;
            if (position.Hours >= 1)
            {
                txtBlock1.Text = string.Format("{0:d2}:{1:d2}:{2:d2}", position.Hours, position.Minutes, position.Seconds);
            }
            else
            {
                txtBlock1.Text = string.Format("{0:d2}:{1:d2}", position.Minutes, position.Seconds);
            }

            TimeSpan timeRemaining = new TimeSpan();
            timeRemaining = PlayerVideo.NaturalDuration.TimeSpan - position;
            if (position.Hours >= 1)
            {
                txtBlock2.Text = string.Format("-{0:d2}:{1:d2}:{2:d2}", timeRemaining.Hours, timeRemaining.Minutes, timeRemaining.Seconds);
            }
            else
            {
                txtBlock2.Text = string.Format("-{0:d2}:{1:d2}", timeRemaining.Minutes, timeRemaining.Seconds);
            }
        }

        private void IntMedia()
        {
            _mediaPlayerLauncher = new MediaPlayerLauncher();
            _mediaPlayerLauncher.Location = MediaLocationType.Install;
            _mediaPlayerLauncher.Controls = MediaPlaybackControls.All;
            _mediaPlayerLauncher.Orientation = MediaPlayerOrientation.Landscape;

            ImageTools.IO.Decoders.AddDecoder<GifDecoder>();

            imgLoading.Source = new ExtendedImage() { UriSource = new Uri("/Assets/Icons/loading_video.gif", UriKind.Relative) };
        }

        private void SetupTimer()
        {
            _timer = new DispatcherTimer();
            StartTimer();
        }

        private void StartTimer()
        {
            _timer.Tick += _timer_Tick;
            _timer.Start();
        }

        private void _timer_Tick(object sender, object e)
        {
            UpdateState(null, null);
        }

        private void PlayOneVideo(string temp)
        {        
            _mediaPlayerLauncher.Media = new Uri(temp, UriKind.RelativeOrAbsolute);
            PlayerVideo.Source = new Uri(temp, UriKind.RelativeOrAbsolute);
            VideoName.Text = _listVideo[_currentVideo].VideoName;
            SingerName.Text = _listVideo[_currentVideo].SingerName;
        }

        private void LoadListVideos(NavigationEventArgs e)
        {
            _listVideo = new List<iMusik.Mp3ZingOnline.Mp3Video>();

            try
            {
                _listVideo.Add(PhoneApplicationService.Current.State["param"] as iMusik.Mp3ZingOnline.Mp3Video);
                PlayOneVideo(_listVideo[_currentVideo].DirectLink);
            }
            catch
            {
                MessageBox.Show("Error");
            }

            UpdateButtons(false, true, true);

            if (_listVideo.Count == 1)
            {
                UpdateButtons(false, true, false);
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (_count == 0)
            {
                _count++;
                LoadListVideos(e);
                return;
            }

        }

        private void PlayerVideo_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            UpdatePlayButton();
            if (PlayerVideo.CurrentState == MediaElementState.Playing)
            {
                imgLoading.Stop();
                imgLoading.Opacity = 0;
                imgPause.Opacity = 0;
                _timer.Start();
                return;
            }

            if (PlayerVideo.CurrentState == MediaElementState.Paused || PlayerVideo.CurrentState == MediaElementState.Stopped)
            {
                imgPause.Opacity = 40;
                imgLoading.Opacity = 0;
                _timer.Stop();
                return;
            }

            if (PlayerVideo.CurrentState == MediaElementState.Opening)
            {
                imgPause.Opacity = 40;
                imgLoading.Opacity = 0;
                return;
            }

            if (PlayerVideo.CurrentState == MediaElementState.Buffering)
            {
                imgPause.Opacity = 0;
                imgLoading.Opacity = 40;
                imgLoading.Start();
            }

        }

        private void PlayerVideo_MediaOpened(object sender, RoutedEventArgs e)
        {
            sldPosition.Maximum = (int)PlayerVideo.NaturalDuration.TimeSpan.TotalSeconds;
            SetupTimer();
        }

        private void PlayerVideo_MediaEnded(object sender, RoutedEventArgs e)
        {
            PlayerVideo.Stop();
            _timer.Stop();
            UpdateState(null, null);

            if (_listVideo.Count >= 2 && _currentVideo < _listVideo.Count - 1)
            {
                PlayOneVideo(_listVideo[++_currentVideo].DirectLink);
                PlayerVideo.AutoPlay = true;
            }
            UpdateBackAndNextButtons();
        }

        private void PlayerVideo_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MessageBox.Show("Error");
        }

        private void sldPosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sldPosition != null && e.NewValue - e.OldValue != 1.0)
            {
                TimeSpan ts = new TimeSpan(0, 0, (int)sldPosition.Value);
                PlayerVideo.Position = ts;
            }
        }

        private void preButton_Click(object sender, EventArgs e)
        {
            if (_currentVideo == 0)
                return;
            PlayOneVideo(_listVideo[--_currentVideo].DirectLink);
            if (_currentVideo == 0)
                UpdateButtons(false, true, true);
            else
                UpdateButtons(true, true, true);
        }

        private void playButton_Click(object sender, EventArgs e)
        {
            if (PlayerVideo.CurrentState == MediaElementState.Playing)
            {
                PlayerVideo.Pause();
            }
            else
            {
                PlayerVideo.Play();
            }
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            if (_currentVideo + 1 == _listVideo.Count)
                return;
            PlayOneVideo(_listVideo[++_currentVideo].DirectLink);
            if (_currentVideo == _listVideo.Count - 1)
                UpdateButtons(true, true, false);
            else
                UpdateButtons(true, true, true);
        }

        private void grdVideo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (PlayerVideo.CurrentState == MediaElementState.Playing)
            {
                PlayerVideo.Pause();
            }
            else
            {
                PlayerVideo.Play();
            }
        }

        private void grdVideo_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            PlayerVideo.Stop();
            _mediaPlayerLauncher.Show();
        }

    }
}